<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.householdPopulation_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
    </avue-crud>

     <el-dialog title="选择坐标点"
      ref="gridDialog"
        append-to-body
        :visible.sync="mapBox"
        :fullscreen="false"
        style="width:100%;height:900px;">
      <coordinate-map style="height:600px;" v-on:getGridData="getGridMap($event)" :lngv="form.lng ? form.lng :''" :latv="form.lat ? form.lat :''" />
    </el-dialog>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/ninebasic/realpop/householdPopulation";
  import {mapGetters} from "vuex";
  import { validatenull,isvalidatemobile,cardid,isMobile} from "@/util/validate";
  import { getHouseList } from "@/api/ninebasic/realpop/house";
  //打点坐标组件
  import coordinateMap from '@/components/gis/coordinateMap'
  export default {
    data() {
       //手机号校验非空
      const validatePhone = (rule, value, callback) => {
        if (isvalidatemobile(value)[0]) {
          callback(new Error(isvalidatemobile(value)[1]));
        } else {
          callback();
        }
      };
      //校验格式手机号  
      const validatePhoneFex = (rule, value, callback) => {
        if(!validatenull(value)){
            if (!isMobile(value)) {
              callback("手机号格式错误");
            } else {
              callback();
            }
        }else{
           callback();
        }
      };
     
      //校验身份正号码
      const validateCardid = (rule, value, callback) => {
        if(cardid(value)[0]){
          callback(new Error(cardid(value)[1]))
        }else{
          callback();
        }
      };
      return {
        lngv: "",
        latv: "",
        mapBox: false,
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height: 'auto',
          calcHeight: 30,
          dialogWidth: 1250,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          excelBtn: true,
          dialogClickModal: false,
          column: [
            {
              label: "头像",
              prop: "photoLink",
              type: 'upload',
              listType: 'picture-img',
              action: '/api/smart-resource/oss/endpoint/put-file',
              propsHttp: {
                res: 'data',
                url: 'link',
              },
              hide: true,
              span: 24,
            },
           {
              label: "所属网格",
              prop: "gridId",
              type: "tree",
              span: 24,
              parent: true,
              display: true,
              dicMethod: "get",
              dicUrl: "/api/smart-system/dept/treeByPid",
              props: {
                label: "title"
              
              },
              checkStrictly: true,
              search: true,
              rules: [{
                required: true,
                message: "请输入所属网格",
                trigger: "click"
              }],
            },
            {
              label: "房屋",
              prop: "houseId",
              type: "select",
              hide: true,
              span: 8,
               dicData: [],
               props: {
                    label: "title",
                    value: "key"
                  },
              rules: [{
                required: true,
                message: "请输入房屋",
                trigger: "blur"
              }],
            },
            {
              label: "身份号码",
              prop: "idCardNo",
              type: "input",
              hide: true,
              span: 8,
              rules: [{
                required: true,
                validator: validateCardid,
                //message: "请输入身份号码",
                trigger: "blur"
              }],
              blur: ({value}) => {
                //this.$message.success(value,column)
                this.form.birthday  = value.substring(6,10)+"-"+value.substring(10,12)+"-"+value.substring(12,14);
                this.form.sex = value.substring(16,17)%2===0?'2':'1';
              }
            },
            {
              label: "姓名",
              prop: "name",
              type: "input",
              search: true,
              span: 8,
              rules: [{
                required: true,
                message: "请输入姓名",
                trigger: "blur"
              }],
            },
            {
              label: "曾用名",
              prop: "usedName",
              type: "input",
              span: 8,
              hide: true,
            },
            {
              label: "性别 ",
              prop: "sex",
              type: "select",
              dicUrl: "/api/smart-system/dict/dictionary?code=sex",
              span: 8,
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              search: true,
              rules: [{
                required: true,
                message: "请输入性别 ",
                trigger: "blur"
              }],
            },
            {
              label: "出生日期",
              prop: "birthday",
              type: "date",
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd",
              span: 8,
              search: true,
              rules: [{
                required: true,
                message: "请输入出生日期",
                trigger: "blur"
              }],
            },
            {
              label: "民族",
              prop: "nation",
              type: "select",
              dicUrl: "/api/smart-system/dict/dictionary?code=nation",
              span: 8,
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              hide: true,
              rules: [{
                required: true,
                message: "请输入民族",
                trigger: "blur"
                
              }],
            },
            {
              label: "籍贯",
              prop: "nativePlace",
              type: "input",
              hide: true,
              span: 8,
              rules: [{
                required: true,
                message: "请输入籍贯",
                trigger: "blur"
              }],
            },
            {
              label: "婚姻状况",
              prop: "marriage",
              type: "select",
              dicUrl: "/api/smart-system/dict/dictionary?code=marital_status",
              span: 8,
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              hide: true,
              rules: [{
                required: true,
                message: "请输入婚姻状况",
                trigger: "blur"
              }],
            },
            {
              label: "政治面貌",
              prop: "politics",
              type: "select",
              dicUrl: "/api/smart-system/dict/dictionary?code=party",
              span: 8,
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              hide: true,
              rules: [{
                required: true,
                message: "请输入政治面貌",
                trigger: "blur"
              }],
            },
            {
              label: "学历",
              prop: "education",
              type: "select",
              dicUrl: "/api/smart-system/dict/dictionary?code=education",
              span: 8,
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              hide: true,
              rules: [{
                required: true,
                message: "请输入学历",
                trigger: "blur"
              }],
            },
            {
              label: "宗教信仰",
              prop: "religion",
              type: "select",
              dicUrl: "/api/smart-system/dict/dictionary?code=religion",
              span: 8,
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              hide: true,
              rules: [{
                required: true,
                message: "请输入宗教信仰",
                trigger: "blur"
              }],
            },
            {
              label: "职业类别",
              prop: "professionType",
              type: "input",
              hide: true,
              span: 8,
              rules: [{
                required: true,
                message: "请输入职业类别",
                trigger: "blur"
              }],
            },
            {
              label: "职业",
              prop: "profession",
              type: "input",
              hide: true,
              span: 8,
              rules: [{
                required: true,
                message: "请输入职业",
                trigger: "blur"
              }],
            },
            {
              label: "工作单位",
              prop: "serviceSpace",
              type: "input",
              span: 8,
              hide: true,
            },
            {
              label: "联系方式",
              prop: "mobile",
              type: "input",
              search: true,
              span: 8,
              rules: [{
                required: true,
                validator: validatePhone,
                //message: "请输入联系方式",
                trigger: "blur"
              }],
            },
            {
              label: "户籍地",
              prop: "householdAddr",
              //type: "select",
              type: "input",
              hide: true,
              span: 8,
              rules: [{
                required: true,
                message: "请输入户籍地",
                trigger: "blur"
              }],
            },
            {
              label: "户籍详址",
              prop: "householdAddrDetail",
              type: "input",
              hide: true,
              span: 8,
              rules: [{
                required: true,
                message: "请输入户籍详址",
                trigger: "blur"
              }],
            },
            {
              label: "现住地",
              prop: "liveAddr",
              //type: "select",
              type: "input",
              hide: true,
              span: 8,
              rules: [{
                required: true,
                message: "请输入现住地",
                trigger: "blur"
              }],
            },
            {
              label: "现住详址",
              prop: "liveAddrDetail",
              type: "input",
              hide: true,
              span: 8,
              rules: [{
                required: true,
                message: "请输入现住详址",
                trigger: "blur"
              }],
            },
           
           {
              label: "经度",
              prop: "lng",
              type: "input",
              hide: true,
              suffixIcon:'el-icon-map-location',
              props: {
                label: "lng",
                value: ""
              },
              // rules: [{
              //   required: false,
              //   message: "请选择坐标点",
              //   trigger: "click"
              // }],
              click:()=>{
                this.openGrid()
              }
            },
            {
              label: "纬度",
              prop: "lat",
              type: "input",
              hide: true,
              suffixIcon:'el-icon-map-location',
              props: {
                label: "lat",
                value: ""
              },
              // rules: [{
              //   required: false,
              //   message: "请选择坐标点",
              //   trigger: "click"
              // }],
              click:()=>{
                this.openGrid()
              }
            },
           {
                  label: "是否留守人员",
                  prop: "isStay",
                  type: "radio",
                  span: 8,
                  search: true,
                  dicData: [
                        {
                          label: "是",
                          value: "1"
                        },
                        {
                          label: "否",
                          value: "2"
                        }
                  ],
                },
                {
                  label: "人户一致",
                  prop: "peopleInHouseholdsFlag",
                  type: "select",
                  span: 8,
                  dicData: [
                    {
                      label: "一致",
                      value: "1"
                    },
                    {
                      label: "不一一致",
                      value: "2"
                    }
                  ],
                  hide: true,
                },
                {
                  label: "户号",
                  prop: "householdNo",
                  type: "input",
                  span: 8,
                  hide: true,
                },
                {
                  label: "户主身份证",
                  prop: "householderIdCard",
                  type: "input",
                  span: 8,
                  hide: true,
                },
                {
                  label: "户主姓名",
                  prop: "householderName",
                  type: "input",
                  span: 8,
                  hide: true,
                },
                {
                  label: "与户主关系",
                  prop: "relation",
                  type: "select",
                  dicUrl: "/api/smart-system/dict/dictionary?code=household_relation",
                  span: 8,
                  props: {
                    label: "dictValue",
                    value: "dictKey"
                  },
                  hide: true,
                },
                {
                  label: "户主联系方式",
                  prop: "householderContact",
                  type: "input",
                  span: 8,
                  hide: true,
                  rules: [{
                       validator: validatePhoneFex,
                       trigger: "blur"
                  }],
                },
                
                {
                  label: "健康情况",
                  prop: "healthy",
                  type: "select",
                  dicUrl: "/api/smart-system/dict/dictionary?code=health_case",
                  display: false,
                  span: 8,
                  props: {
                    label: "dictValue",
                    value: "dictKey"
                  },
                  hide: true,
                },
                {
                  label: "个人收入情况",
                  prop: "personalIncome",
                  type: "input",
                  span: 8,
                  hide: true,
                  display: false,
                },
                {
                  label: "留守类型",
                  prop: "stayType",
                  type: "select",
                  display: false,
                  search: true,
                  span: 8,
                  dicUrl: "/api/smart-system/dict/dictionary?code=rear_personnel",
                  props: {
                    label: "dictValue",
                    value: "dictKey"
                  },
                },
                {
                  label: "家庭成员身份号码",
                  prop: "mainCard",
                  type: "input",
                  span: 8,
                  hide: true,
                  display: false,
                },
                {
                  label: "家庭成员姓名",
                  prop: "mainName",
                  type: "input",
                  span: 8,
                  hide: true,
                  display: false,
                },
                {
                  label: "家庭成员健康情况",
                  prop: "mainHealthy",
                  type: "input",
                  dicUrl: "/api/smart-system/dict/dictionary?code=health_case",
                  display: false,
                  span: 8,
                  props: {
                    label: "dictValue",
                    value: "dictKey"
                  },
                  hide: true,
                },
                {
                  label: "与留守人员关系",
                  prop: "stayRelation",
                  type: "select",
                  dicUrl: "/api/smart-system/dict/dictionary?code=household_relation",
                  span: 8,
                  display: false,
                  props: {
                    label: "dictValue",
                    value: "dictKey"
                  },
                  hide: true,
                },
                {
                  label: "成员联系方式",
                  prop: "mainContact",
                  type: "input",
                  span: 8,
                  hide: true,
                  display: false,
                },
                {
                  label: "成员工作地址",
                  prop: "mainWorkAdd",
                  type: "input",
                  span: 8,
                  hide: true,
                  display: false,
                },
                {
                  label: "家庭年收入",
                  prop: "income",
                  type: "input",
                  span: 8,
                  hide: true,
                  display: false,
                },
                {
                  label: "困难及诉求",
                  prop: "demand",
                  type: "textarea",
                  span: 24,
                  hide: true,
                  display: false,
                },
                {
                  label: "帮扶情况",
                  prop: "supportCase",
                  type: "textarea",
                  span: 24,
                  hide: true,
                  display: false,
                },
            //   {
            //   label: "人口类型",
            //   prop: "populationType",
            //   type: "select",
            //   search: true,
            //   span: 8,
            //   addDisplay: false,
            //   editDisplay: false,
            //   viewDisplay: true,
            //   rules: [{
            //     required: true,
            //     message: "请输入人口类型",
            //     trigger: "blur"
            //   }],
            //   dicData: [
            //     {
            //       label: "户籍人口",
            //       value: "1"
            //     },
            //     {
            //       label: "流动人口",
            //       value: "2"
            //     },
            //      {
            //       label: "外籍人口",
            //       value: "2"
            //     }
            //   ],
            // },
          ]
        },
        data: []
      };
    },
    watch: {
        'form.gridId'() {
            if (!validatenull(this.form.gridId)) {
                getHouseList(this.form.gridId).then(res => {
                  const column = this.findObject(this.option.column, "houseId");
                  column.dicData = res.data.data;
                });
            }
        },
        'form.isStay': {      
          handler(val){
            var healthy =this.findObject(this.option.column,"healthy");
            var stayType=this.findObject(this.option.column,"stayType");
            var mainCard=this.findObject(this.option.column,"mainCard");
            var mainName=this.findObject(this.option.column,"mainName");
            var mainHealthy=this.findObject(this.option.column,"mainHealthy");
            var stayRelation=this.findObject(this.option.column,"stayRelation");
            var mainContact=this.findObject(this.option.column,"mainContact");
            var mainWorkAdd=this.findObject(this.option.column,"mainWorkAdd");
            var income=this.findObject(this.option.column,"income");
            var demand=this.findObject(this.option.column,"demand");
            var supportCase=this.findObject(this.option.column,"supportCase");
            var personalIncome=this.findObject(this.option.column,"personalIncome");
            if(val==1){
              
              healthy.display = true;
              stayType.display = true;
              mainCard.display = true;
              mainName.display = true;
              mainHealthy.display = true;
              stayRelation.display = true;
              mainContact.display = true;
              mainWorkAdd.display = true;
              income.display = true;
              demand.display = true;
              supportCase.display = true;
              personalIncome.display = true;
              }else{
              healthy.display = false;
              stayType.display = false;
              mainCard.display = false;
              mainName.display = false;
              mainHealthy.display = false;
              stayRelation.display = false;
              mainContact.display = false;
              mainWorkAdd.display = false;
              income.display = false;
              demand.display = false;
              supportCase.display = false;
              personalIncome.display = false;
              }
          },
        },  
      },
   components:{
      coordinateMap
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.householdPopulation_add, false),
          viewBtn: this.vaildData(this.permission.householdPopulation_view, false),
          delBtn: this.vaildData(this.permission.householdPopulation_delete, false),
          editBtn: this.vaildData(this.permission.householdPopulation_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
       openGrid(){
        this.mapBox = true
      },

      //地图选择组件回调处理数据
      getGridMap(data){
        console.log("callback:",data)

        if(data){
          this.form.lng = data.lng
          this.form.lat = data.lat
        }

        this.mapBox = false
      },
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        //新增和修改页面，控制网格树加载职能选择末级，查询页面可以选择父级
        if (["edit", "add"].includes(type)) {
            const gridId = this.findObject(this.option.column,"gridId");
            gridId.parent = false;
           
        }
        if (["add"].includes(type)) {
          setTimeout(() => {
            this.form.populationType = '1';
          }, 10);
        }
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
.el-form-item__content{
   margin-left: 130px ! important;
}
.el-form-item__label {
  width: 130px ! important;
}
</style>
